package com.yenlien.traceyun.business.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yenlien.traceyun.business.bean.Search;
import com.yenlien.traceyun.business.controller.response.WarehousePartView;
import com.yenlien.traceyun.business.controller.response.WarehouseTree;
import com.yenlien.traceyun.business.dao.BaseSoilDao;
import com.yenlien.traceyun.business.dao.WarehouseDao;
import com.yenlien.traceyun.business.dao.WarehousePartDao;
import com.yenlien.traceyun.business.entity.BaseSoil;
import com.yenlien.traceyun.business.entity.Warehouse;
import com.yenlien.traceyun.business.entity.WarehousePart;
import com.yenlien.traceyun.business.interceptor.UserAuthUtil;
import com.yenlien.traceyun.webase.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.*;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: bigwangy@sina.com
 * @create: 2020-12-21
 * @description:
 **/

@Service
public class WarehouseService {

    @Autowired
    private WarehouseDao warehouseDao;

    @Autowired
    private WarehousePartDao warehousePartDao;

    @Autowired
    private BaseSoilDao baseSoilDao;

    /**
     * 保存仓库信息
     *
     * @param warehouse
     * @param parts
     * @return
     */
    public Warehouse save(Warehouse warehouse, List<WarehousePart> parts, BaseSoil baseSoil) {
        warehouse.setCompanyId(UserAuthUtil.getLoginUser().getCompanyId());
        if (!StringUtils.isEmpty(warehouse.getId())) {
            warehousePartDao.deleteByWarehouseId(warehouse.getId());
        }
        warehouse.setBasesoilId(baseSoil.getId());
        Warehouse p = warehouseDao.save(warehouse);
        if (parts != null && parts.size() > 0) {
            for (WarehousePart item : parts) {
                item.setWarehouseId(p.getId());
                item.setCompanyId(warehouse.getCompanyId());
            }
            warehousePartDao.saveAll(parts);
        }
        return p;
    }


    public JSONObject pageDetail(Search search) {
        search.setCompanyId(UserAuthUtil.getLoginUser().getCompanyId());
        Pageable pageable = PageRequest.of(search.getPageno() == -1 ? 0 : search.getPageno(), search.getPagesize(), Sort.Direction.DESC, "warehouseId", "createtime");
        Page<WarehousePart> pages = warehousePartDao.findAll(create(search), pageable);
        JSONObject result = new JSONObject();
        List<WarehousePartView> parts = null;
        if (pages.getContent() != null && pages.getContent().size() > 0) {
            Set<String> warehouseIds = pages.getContent().stream().map(p -> p.getWarehouseId()).collect(Collectors.toSet());
            List<Warehouse> warehouses = warehouseDao.findByIdIn(warehouseIds);
            parts = WarehousePartView.create(pages.getContent());
            Set<String> basesoildIds = warehouses.stream().map(p -> p.getBasesoilId()).collect(Collectors.toSet());
            List<BaseSoil> baseSoils = baseSoilDao.findByIdIn(basesoildIds);
            Set<String> setPids = baseSoils.stream().map(p -> p.getPid()).collect(Collectors.toSet());
            List<BaseSoil> basePidSoils = baseSoilDao.findByIdIn(setPids);
            for (WarehousePartView view : parts) {
                if (view.getWarehouseId() != null) {
                    for (Warehouse warehouse : warehouses) {
                        if (view.getWarehouseId().equals(warehouse.getId())) {
                            view.setWarehouse(warehouse.getName());
                            view.setBasesoilId(warehouse.getBasesoilId());
                            break;
                        }
                    }
                }

                if (view.getBasesoilId() != null) {
                    for (BaseSoil baseSoil : baseSoils) {
                        if (view.getBasesoilId() != null && view.getBasesoilId().equals(baseSoil.getId())) {
                            if (StringUtils.isEmpty(baseSoil.getPid())) {
                                view.setBasesoild(baseSoil.getName());
                            } else {
                                for (BaseSoil p : basePidSoils) {
                                    if (baseSoil.getPid().equals(p.getId())) {
                                        view.setBasesoild(p.getName());
                                        break;
                                    }
                                }
                            }
                            break;
                        }
                    }
                }
            }
        }
        result.put("rows", parts);
        result.put("total", pages.getTotalElements());
        return result;
    }

    public Specification create(Search search) {
        return new Specification<WarehousePart>() {
            private static final long serialVersionUID = 1L;

            @Override
            public Predicate toPredicate(Root<WarehousePart> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                //构造查询条件
                List<Predicate> list = new ArrayList<>();
                if (!StringUtils.isEmpty(search.getKey())) {
                    list.add(cb.equal(root.get("name"), search.getKey()));
                }
                if (!StringUtils.isEmpty(search.getCompanyId())) {
                    list.add(cb.equal(root.get("companyId"), search.getCompanyId()));
                }
                Predicate[] predicate = new Predicate[list.size()];
                return cb.and(list.toArray(predicate));
            }
        };
    }

    public JSONArray trees() {
        String companyId = UserAuthUtil.getLoginUser().getCompanyId();

        JSONArray jd = new JSONArray();
        List<BaseSoil> baseSoil1 = baseSoilDao.finByBasesoilId(companyId);      //基地信息
        for (BaseSoil baseSoil : baseSoil1) {
            String baseSoil_id = baseSoil.getId();
            if (StringUtils.isEmpty(baseSoil_id)) {
                continue;
            }
            List<WarehousePart> parts = warehousePartDao.findByBasesoilId(baseSoil_id);       //仓位
            if (parts != null && parts.size() > 0) {
                JSONArray cw = new JSONArray();
                for (WarehousePart part : parts) {
                    cw.add(part);       //仓库有多个仓位
                }
                String s = JSONObject.toJSONString(baseSoil);
                JSONObject jdObj = JSONObject.parseObject(JSONObject.toJSONString(baseSoil));
                jdObj.put("cw", cw);
                jd.add(jdObj);     //一个基地有多个仓库(  基地的仓位信息)
            }

        }
        return jd;
    }
}
